<?php

namespace app\system\service;

use app\system\model\UserModel;
use think\facade\Db;

class LoginService
{


    /**
     * 描述: 校验用户名和密码
     * 参数: {
     *       "username": 用户名,
     *       "password": 密码,
     *      }
     * 返回: []
     * 作者: Feng
     */
    public static function validateAccount($username, $password)
    {
        try {
            // 尝试获取用户信息
//            $user = UserModel::where('username', $username)->findOrEmpty()->toArray();;
            $user =  UserModel::alias('u')
                ->leftJoin('user_roles ur', 'u.id = ur.userId')
                ->leftJoin('roles r', 'ur.roleId = r.id')
                ->where('u.username', $username)
                ->field('u.*, GROUP_CONCAT(r.code) as roles')
                ->group('u.id')
                ->findOrEmpty()
                ->toArray();

            // 用户名不存在
            if (empty($user)) {
                return (['success' => false, 'info' => '用户名不存在!']);
            }
            if ($user['status']== 0) {
                return (['success' => false, 'info' => '用户已禁用!']);
            }
            if ($user['loginfailure'] >= 10 && time() - $user['updatetime'] < 86400) {
                return (['success' => false, 'info' => '请在1天后重试!']);
            }

            // 密码验证
            if ($user['password'] != md5(md5($password) . $user['salt'])) {
                return (['success' => false, 'info' => '密码错误!']);
            }
        } catch (\Exception $e) {
            // 异常处理
            return (['success' => false, 'info' => $e->getMessage()]);
        }
        // 验证成功
        return (['success' => true, 'info' => '验证成功!','data'=>$user]);
    }

}